package tech.runchen.gz5055.oms.common.utils;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author zzj
 */
public class OrderUtils {

    private static int counter = 0;
    private static final int PREFIX_LENGTH = 4;
    private static final int DATE_LENGTH = 8;
    private static final int SEQUENCE_LENGTH = 4;

    public static String generateOrderNumber(long userId) {
        String datePart = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String sequencePart = String.format("%04d", getNextSequence());
        String orderNumber = datePart + String.format("%04d", userId) + sequencePart;
        String checkDigit = calculateCheckDigit(orderNumber);
        return orderNumber + checkDigit;
    }

    private static synchronized int getNextSequence() {
        if (counter >= 9999) {
            counter = 0;
        }
        return ++counter;
    }

    private static String calculateCheckDigit(String orderNumber) {
        int sum = 0;
        for (int i = 0; i < orderNumber.length(); i++) {
            sum += orderNumber.charAt(i);
        }
        return String.valueOf(sum % 10);
    }
}
